package com.itlong.cloud.controller.home;

import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.property.app.PropertyAppUserInfoVO;
import com.itlong.cloud.POJO.VO.app.property.app.PropertyAppUserProjectInfoVO;
import com.itlong.cloud.POJO.VO.operate.OperateAdImgVO;
import com.itlong.cloud.POJO.VO.property.PropertyProjectBuildSimpleInfoVO;
import com.itlong.cloud.POJO.VO.property.PropertyProjectRoomSimpleInfoVO;
import com.itlong.cloud.POJO.VO.property.PropertyProjectUnitSimpleInfoVO;
import com.itlong.cloud.POJO.VO.property.PropertyUserCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyAppErrorCodeEnum;
import com.itlong.cloud.project.app.IAppProjectServiceClient;
import com.itlong.cloud.project.operate.IOperateAdManageServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.propertyapp.IPropertyAppMessageServiceClient;
import com.itlong.cloud.user.propertyapp.IPropertyAppUserInfoServiceClient;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      物业app项目模块控制器
 * </desc>
 *
 * @createDate2020/1/2
 **/
@RestController
@RequestMapping("/home")
@RefreshScope
public class PropertyAppProjectController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(PropertyAppHouseholdCheckController.class);

    @Value("${" + PlatformConstants.PROPERTY_APP_USER_TOKEN_KEY + "}")
    public String PROPERTY_APP_USER_TOKEN_KEY;

    @Autowired
    private IPropertyAppUserInfoServiceClient iPropertyAppUserInfoServiceClient;

    @Autowired
    private IOperateAdManageServiceClient iOperateAdManageServiceClient;

    @Autowired
    private IPropertyAppMessageServiceClient iPropertyAppMessageServiceClient;

    @Autowired
    private IAppProjectServiceClient iAppProjectServiceClient;

    @Autowired
    private RedisService<PropertyUserCacheVO> redisService;


    private String userIdSeparator = "_";

    /**
     * <desc>
     *      获取登录用户的项目列表
     * </desc>
     *
     * @param token
     * @return
     * @Author Zhu.yj
     * @createDate  2020/1/2
     */
    @ResponseBody
    @RequestMapping(value = "/getAllProject",method = RequestMethod.POST)
    public Object getAllProject(String token){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            //从缓存取出用户信息
            if (StringUtils.isBlank(token)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            PropertyUserCacheVO propertyUserCacheVO = iPropertyAppUserInfoServiceClient.retrieve(token);
            //取出该账号下的项目列表
            List<PropertyAppUserProjectInfoVO> projectMapList = iPropertyAppUserInfoServiceClient.getProjectListByUserId(propertyUserCacheVO.getUserId());
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (PropertyAppUserProjectInfoVO propertyAppUserProjectInfoVO : projectMapList){
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("projectId",propertyAppUserProjectInfoVO.getProjectId());
                resultMap.put("projectName",propertyAppUserProjectInfoVO.getProjectName());
                resultList.add(resultMap);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultList);
        }catch (Exception e){
            throw new DataAccessException("【物业APP_首页板块_获取项目】获取项目列表失败",e);
        }
    }

    /**
     * <desc>
     *      获取用户信息或者切换项目
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2020/1/2
     */
    @ResponseBody
    @RequestMapping(value = "getUserInfo",method = RequestMethod.POST)
    public Object getUserInfo(String token, String projectId){
        try{
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            //从缓存中获取用户基本信息
            PropertyUserCacheVO propertyUserCacheVO = iPropertyAppUserInfoServiceClient.retrieve(token);
            //切换项目
            if (StringUtils.isNotBlank(projectId)){
                //找出当前用户所拥有的项目列表
                List<PropertyAppUserProjectInfoVO> projectInfoVOList = iPropertyAppUserInfoServiceClient.getProjectListByUserId(propertyUserCacheVO.getUserId());
                boolean flag = false;
                for (PropertyAppUserProjectInfoVO propertyAppUserProjectInfoVO : projectInfoVOList){
                    if (propertyAppUserProjectInfoVO.getProjectId().equals(projectId)){
                        if (propertyAppUserProjectInfoVO.getStatus().equals("2")){
                            return new MessageVO(AppErrorCodeEnum.PAD_PROJECT_FORBIDDEN.getErrorCode());
                        }
                        propertyUserCacheVO.setProjectId(projectId);
                        propertyUserCacheVO.setProjectName(propertyAppUserProjectInfoVO.getProjectName());
                        propertyUserCacheVO.setPubKey(propertyAppUserProjectInfoVO.getPubKey());
                        propertyUserCacheVO.setTalkLimit(propertyAppUserProjectInfoVO.getTalkLimit());
                        propertyUserCacheVO.setWatchLimit(propertyAppUserProjectInfoVO.getWatchLimit());
                        flag = true;
                        redisService.set(RedisConstant.PROPERTY_APP_REDIS_USER_KEY+propertyUserCacheVO.getUserId(), RedisConstant.PROPERTY_APP_LOGIN_TIME, propertyUserCacheVO);
                        break;
                    }
                }
                if (!flag){
                    return new MessageVO(PropertyAppErrorCodeEnum.PROJECT_NOT_EXISTS.getErrorCode());
                }
                //切换项目成功之后将当前项目保存到用户信息表中
                iPropertyAppUserInfoServiceClient.updateCurrentProjectId(projectId,propertyUserCacheVO.getUserId());
            }
            PropertyAppUserInfoVO propertyAppUserInfoVO = new PropertyAppUserInfoVO();
            propertyAppUserInfoVO.setCardLevel(propertyUserCacheVO.getCardLevel());
            //需求变更，字段值由userName变更为realName
            propertyAppUserInfoVO.setUserName(propertyUserCacheVO.getRealName());
            propertyAppUserInfoVO.setPhotoUrl(propertyUserCacheVO.getPhotoUrl());
            //获取第三方token信息
            String clientToken = iPropertyAppUserInfoServiceClient.getUserClientToken(propertyUserCacheVO.getUserId());
            if (clientToken == null){
                propertyAppUserInfoVO.setClientToken("");
            }
            else {
                propertyAppUserInfoVO.setClientToken(clientToken);
            }
            propertyAppUserInfoVO.setPhoneNo(propertyUserCacheVO.getPhoneNum());
            propertyAppUserInfoVO.setPubKey(propertyUserCacheVO.getPubKey());
            propertyAppUserInfoVO.setCurProjectId(propertyUserCacheVO.getProjectId());
            propertyAppUserInfoVO.setCurProjectName(propertyUserCacheVO.getProjectName());
            propertyAppUserInfoVO.setTalkLimit(propertyUserCacheVO.getTalkLimit());
            propertyAppUserInfoVO.setWatchLimit(propertyUserCacheVO.getWatchLimit());
            propertyAppUserInfoVO.setHasNewMsg(propertyUserCacheVO.getHasNewMsg());
            propertyAppUserInfoVO.setToken(propertyUserCacheVO.getToken());

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),StringHandlerUtil.formatString(propertyAppUserInfoVO));
        }catch (Exception e){
            throw new DataAccessException("【物业APP-首页-获取用户信息或切换项目getUserInfo】获取用户信息或切换项目失败",e);
        }
    }

    /**
     * <desc>
     *      获取该项目下所有banner图片
     * </desc>
     *
     * @param token 用户登陆凭证
     * @param projectId 项目id
     * @return
     * @Author Zhu.yj
     * @createDate  2020/1/14
     */
    @ResponseBody
    @RequestMapping(value = "/getBanner",method = RequestMethod.POST)
    public Object getBanner(String token,String projectId,HttpServletRequest request){
        try {
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            if (StringUtils.isBlank(token) || StringUtils.isBlank(projectId)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!projectId.matches("[0-9]{8}")) {
                return new MessageVO(AppErrorCodeEnum.PROJECT_NOT_MATCH.getErrorCode());
            }
            List<OperateAdImgVO> adImgVOS = iOperateAdManageServiceClient.getBannerImgs(projectId, 1,3);
            //获取公告消息列表
            List<String> propertyNotice = iPropertyAppMessageServiceClient.getNoticeContent(projectId);
            Map<String, Object> resultMap = new HashMap<>();
            List<Map<String, Object>> imageMapList = new ArrayList<>();
            //处理null值
            if (adImgVOS != null && adImgVOS.size()>0) {
                for (OperateAdImgVO img: adImgVOS){
                    Map<String, Object> result = new HashMap<>();
                    StringHandlerUtil.formatString(img);
                    result.put("imageUrl",img.getImgUrl());
                    result.put("linkUrl",img.getJumpUrl());
                    imageMapList.add(result);
                }
            }
            if (propertyNotice == null){
                propertyNotice = new ArrayList<>();
            }

            resultMap.put("notice", propertyNotice);
            resultMap.put("imageAry", imageMapList);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        } catch (Exception e) {
            throw new DataAccessException("【物业app-首页-项目模块getBanner】,获取Banner失败", e);
        }
    }

    /**
     * <desc>
     *      根据项目id获取楼栋id
     * </desc>
     *
     * @param projectId 项目id
     * @return
     * @Author Zhu.yj
     * @createDate  2020/3/19
     */
    @RequestMapping(value = "/getBuildList",method = RequestMethod.POST)
    public Object getBuildList(String projectId,HttpServletRequest request){
        try {
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            if (projectId == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!projectId.matches("[0-9]{8}")){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_ID_INVALID_ERR.getErrorCode());
            }
            //复用代码，pageNo和pageSize不起实际作用
            Page<PropertyProjectBuildSimpleInfoVO> page = iAppProjectServiceClient.getBuildsInProject(projectId,"1","15");

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page.getRows());
        }catch (Exception e){
            throw new DataAccessException("【物业app-获取楼栋信息失败getBuildList】获取楼栋信息失败",e);
        }
    }

    /**
     * <desc>
     *      根据楼栋id获取单元信息
     * </desc>
     *
     * @param buildId 楼栋id
     * @param request
     * @return
     * @Author Zhu.yj
     * @createDate  2020/3/19
     */
    @RequestMapping("/getUnitList")
    public Object getUnitList(String buildId,HttpServletRequest request){
        try {
            buildId = request.getAttribute("buildId") == null ? null : request.getAttribute("buildId").toString();
            if (buildId == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Page<PropertyProjectUnitSimpleInfoVO> page = iAppProjectServiceClient.getUnitsInBuild(buildId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page.getRows());
        }catch (Exception e){
            throw new DataAccessException("【物业app-获取单元信息失败getUnitList】获取单元信息失败",e);
        }
    }

    /**
     * <desc>
     *      获取房间信息
     * </desc>
     *
     * @param unitId 项目id
     * @return
     * @Author Zhu.yj
     * @createDate  2020/3/18
     */
    @RequestMapping(value = "/getRoomList",method = RequestMethod.POST)
    public Object getRoomList(String unitId,HttpServletRequest request){
        try{
            unitId = request.getAttribute("unitId") == null ? null : request.getAttribute("unitId").toString();
            if (unitId == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //复用代码，pageNo和pageSize不起实际作用
            Page<PropertyProjectRoomSimpleInfoVO> page = iAppProjectServiceClient.getRoomsInUnit(unitId,"1","15");
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page.getRows());
        }catch (Exception e){
            throw new DataAccessException("【物业app-首页-获取项目下单元房间信息getRoomList】获取房间信息失败",e);
        }
    }


}
